package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //登录操作   http://localhost:8080/backend/page/login/login.html
    @PostMapping("/login")
    public R<Employee> login(HttpServletResponse response,
                             HttpServletRequest request,
                             HttpSession session,
                             @RequestBody Employee employee) {
        //获取用户名,密码;User接收
        //根据用户名查询用户名信息
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        //得到employee对象
        Employee employeeServiceOne = employeeService.getOne(wrapper);

        //判断: 查不到,返回失败
        if (employeeServiceOne == null) {
            return R.error("用户不存在");
        }
        //如果查找,比较密码[密文比对密文[用户铭文MD5]方式]

        //MD5密码
        String pas = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //判断:对比,失败,返回登录失败 谁和谁比啊?????????????
        if (!employeeServiceOne.getPassword().equals(pas)) {
            return R.error("密码错误");
        }
        //比对成功,说明用户名,密码对,则判断,用户是否禁用[0].是返回失败,否返回成功[1]
        if (employeeServiceOne.getStatus() == 0) {
            return R.error("用户禁用,不允许登录");
        }
        //成功则把信息存入session中(用户id)
        //获取request(方法中带形参),再将信息存入session中
        //方法一
//        HttpSession sess = request.getSession();
//        sess.setAttribute("employee",employee.getId());
        //方法二
        session.setAttribute("employee", employeeServiceOne.getId());

        //退出
//        session.removeAttribute("employee");
        // 并且响应结果(用户信息是个对象)
        return R.success(employeeServiceOne);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("employee");
        return R.success("退出成功");
    }



    //定义一个添加方法
    @PostMapping
    public R<String> addEmployee(HttpSession session, @RequestBody Employee employee) {
        //检查前端给的数据全不全
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);


        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //注入session,得到id
        Long id = (Long) session.getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);*/

        //调用业务层的save添加方法完成保存
        employeeService.save(employee);

        return R.success("添加成功,初始密码是123456");
    }


    //分页查询
    @GetMapping("/page")
//    public R<Page<Employee>> pageQueryEmployee(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize,@RequestParam(value = "name" ,required = false)  String name) {
    public R<IPage<Employee>> pageQueryEmployee(Integer page, Integer pageSize, String name) {

        //当前页和每页大小
        IPage<Employee> objectPage = new Page<>(page, pageSize);
        //封装查询条件 where name like '',做模糊查询，查询名字
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //模糊查询，添加条件，
        //  方法一
//        if(name != null && name.length() > 0){
//            wrapper.like(true,Employee::getName,name);
//        }
        //方法二(推荐这么写)
        //StringUtils.isNotEmpty(name) name 不为null
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加默认排序， 默认降序排序(时间），desc
        wrapper.orderByDesc(Employee::getUpdateTime);
        //分页
        employeeService.page(objectPage, wrapper);
        //拿取结果，总页数，列表数据...
        long total = objectPage.getTotal();
        List<Employee> list = objectPage.getRecords();
        //封装一下(方法一)
   /*     HashMap map = new HashMap();
        map.put("total",total);
        map.put("list",list);
        //提示结果
        R.success(map);*/

        //方法二
        return R.success(objectPage);//  objectPage里面就有 total 和 list
    }






    //修改员工信息  （启用禁用接口）

    @PutMapping
    public R<String> updateEmployee(HttpSession session, @RequestBody Employee employee) {
        //优化代码
       /* //修改员工字段(status，Updatetime,updateuser)
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        //修改人
        Long emplyee = (Long) session.getAttribute("employee");
        employee.setUpdateUser(emplyee);

        System.out.println(emplyee);*/
        //修改字段
        employeeService.updateById(employee);
        //返回值employee = {Employee@7586} "Employee(id=1504347180909535233, username=0211, name=111, password=e10adc3949ba59abbe56e057f20f883e, phone=13211111111, sex=1, idNumber=111111111111111111, status=1, createTime=2022-03-17T14:49:09, updateTime=2022-03-17T14:49:09, createUser=1, updateUser=1)"
        return R.success("员工信息修改成功");
    }



    //编辑员工接口
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee byId = employeeService.getById(id);
        return R.success(byId);
    }










}
